package com.winit.project.core.set;

import com.winit.common.util.ConfigUtil;
import com.winit.common.util.ShellRunUtil;
import com.winit.project.core.branch.Branch;
import com.winit.project.core.branch.Project;
import com.winit.project.core.branch.ProjectConfig;
import com.winit.project.core.branch.ProjectStatus;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by wangjian on 16/9/6.
 */
public class ProjectSet {

    private static final Logger logger = LoggerFactory.getLogger(ProjectSet.class);

    private String path;
    private ProjectSetConfig projectSetConfig;
    private String trunkName;

    public ProjectSet(String projectName, boolean loadInfo) throws Exception {
        if (StringUtils.isEmpty(projectName)) {
            logger.error("工程名不能为空");
            throw new Exception("工程名不能为空");
        }
        this.trunkName = ProjectUtil.getTrunkProjectName(projectName);
        this.projectSetConfig = new ProjectSetConfig(this.trunkName, loadInfo);
        this.path = ProjectUtil.getTrunkFilePath(projectName);
    }

    public ProjectSetConfig getProjectSetConfig() {
        return projectSetConfig;
    }

    /**
     * 获取分支工程列表,遍历文件目录
     *
     * @return
     */
    public List<Branch> listBranches(boolean loadInfo) throws Exception {
        logger.info("获取分支工程列表,trunkName=" + this.trunkName);
        File file = new File(this.path);
        if (!file.exists()) {
            logger.error("获取分支工程列表,主目录不存在.trunkName=" + this.trunkName + ",path=" + this.path);
            throw new Exception("获取分支工程列表,主目录不存在.trunkName=" + this.trunkName + ",path=" + this.path);
        }
        List<Branch> list = new ArrayList<>();
        for (File f : file.listFiles()) {
            if (!f.isDirectory()) {
                continue;
            }
            if (!f.getName().startsWith(this.trunkName)) {
                continue;
            }
            list.add(new Project(f.getName(), loadInfo));
        }
        Collections.sort(list, new Comparator<Branch>() {
            @Override
            public int compare(Branch o1, Branch o2) {
                String branch1 = o1.projectName;
                String branch2 = o2.projectName;
                return branch1.compareTo(branch2);
            }
        });
        return list;
    }

    public boolean createBranch(ProjectSetConfig projectSetConfig, ProjectConfig projectConfig) throws Exception {
        logger.info("创建工程主干目录,path=" + this.path);
        File trunkFile = new File(this.path);
        if (trunkFile.exists()) {
            logger.error("创建工程,主干目录已存在.path=" + this.path);
            throw new Exception("创建工程,主干目录已存在.path=" + this.path);
        }
        if (!projectSetConfig.getProjectName().equalsIgnoreCase(projectConfig.getProjectName())) {
            logger.error("创建工程,参数错误.projectName=" + projectSetConfig.getProjectName() + ":" + projectConfig.getProjectName());
            throw new Exception("创建工程,参数错误.projectName=" + projectSetConfig.getProjectName() + ":" + projectConfig.getProjectName());
        }
        if (!this.trunkName.equals(projectSetConfig.getProjectName())) {
            logger.error("创建工程,参数错误.projectName=" + projectSetConfig.getProjectName() + ",trunkName=" + this.trunkName);
            throw new Exception("创建工程,参数错误.projectName=" + projectSetConfig.getProjectName() + ",trunkName=" + this.trunkName);
        }
        trunkFile.mkdirs();
        projectSetConfig.saveToFile();
        return createBranch(projectConfig);
    }

    /**
     * 创建分支工程
     *
     * @param projectConfig
     * @return
     * @throws Exception
     */
    public boolean createBranch(ProjectConfig projectConfig) throws Exception {
        if (!projectConfig.getProjectName().startsWith(this.trunkName)) {
            logger.error("创建分支工程,参数错误.trunkName=" + this.trunkName + ",projectName=" + projectConfig.getProjectName());
            throw new Exception("创建分支工程,参数错误.trunkName=" + this.trunkName + ",projectName=" + projectConfig.getProjectName());
        }
        String path = projectConfig.getPath();
        logger.info("创建分支工程,path=" + path);

        File trunkFile = new File(this.path);
        if (!trunkFile.exists()) {
            logger.error("创建分支工程,主干目录不存在.path=" + this.path);
            throw new Exception("创建分支工程,主干目录不存在.path=" + this.path);
        }

        File file = new File(projectConfig.getPath());
        if (file.exists()) {
            logger.error("创建分支工程,工程已存在.path=" + path);
            throw new Exception("创建分支工程,工程已存在.path=" + path);
        }
        file.mkdirs();
        if (!StringUtils.isEmpty(ConfigUtil.getValue("use_sonar_project")) && ConfigUtil.getValue("use_sonar_project").contains("," + this.trunkName + ",")) {
            projectConfig.setUseSonar(true);
        }
        projectConfig.saveToFile();
        ProjectStatus projectStatus = new ProjectStatus(projectConfig.getProjectName(), false);
        projectStatus.saveToFile();
        //创建构建目录
        Project project = new Project(projectConfig.getProjectName(), false);
        project.createBuildDir();
        return true;
    }

    public String getName() {
        return this.trunkName;
    }

    public Branch getProject(String projectName) throws Exception {
        logger.info("获取分支工程,projectName=" + projectName);
        if (!projectName.startsWith(this.trunkName)) {
            logger.error("获取分支工程,参数错误.trunkName=" + this.trunkName + ",projectName=" + projectName);
            throw new Exception("获取分支工程,参数错误.trunkName=" + this.trunkName + ",projectName=" + projectName);
        }
        return new Project(projectName, true);
    }

    /**
     * 删除工程
     *
     * @param projectName
     * @return
     * @throws Exception
     */
    public boolean delProject(String projectName) throws Exception {
        logger.info("删除工程,projectName=" + projectName);
        if (!projectName.startsWith(this.trunkName)) {
            logger.error("删除工程异常,该工程不在当前主干下.projectName=" + projectName + ",trunkName=" + this.trunkName);
            throw new Exception("删除工程异常,该工程不在当前主干下.projectName=" + projectName + ",trunkName=" + this.trunkName);
        }
        if (projectName.equals(this.trunkName)) {
            logger.error("主干工程不能删除,trunkName=" + this.trunkName);
            throw new Exception("主干工程不能删除,trunkName=" + this.trunkName);
        }

        Project project = new Project(projectName, true);
        String path = project.getPath();
        File file = new File(path);
        if (file.exists()) {
            ShellRunUtil.runCmds("rm", "-rf", path);
        }
        return true;
    }

}
